<template>
  <div>
    <!-- 查询条件和表格区域 -->
    <div>
      <div class="cards">
        <el-select v-model="value" placeholder="请选择品类" style="width: 240px; margin-right: 10px">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-input
            style="width: 240px; margin-right: 10px; text-align: center"
            v-model="data.name"
            placeholder="请输入名称查询"
            :prefix-icon="Search"
        ></el-input>
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="primary" @click="rest">重 置</el-button>
      </div>
      <div v-if="hasSearched" class="card" style="margin-top: 10px">
        <el-table :data="data.tableData" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection" style="border: #666666; width: 10px"></el-table-column>
          <el-table-column label="名称" prop="name" width="120"></el-table-column>
          <el-table-column label="品类" prop="category" width="100"></el-table-column>
          <el-table-column label="进价(元/g)" prop="cost_price"></el-table-column>
          <el-table-column label="售价(元/g)" prop="sale_price"></el-table-column>
          <el-table-column label="规格" prop="standard"></el-table-column>
          <el-table-column label="产地" prop="production" style="label-width: 20px; size: 20px"></el-table-column>
          <el-table-column label="库存量(g)" prop="store_count"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button @click="handleUpdate(scope.row)" type="primary" :icon="ShoppingCart">
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-pagination
              @current-change="load"
              @size-change="load"
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              :page-sizes="[5, 10, 15, 20]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total"
          ></el-pagination>
        </div>
      </div>
      <!-- 未查询时显示的提示 -->
      <div v-else class="no-data-tip">
        暂无数据，请查询
      </div>
      <!--订单-->
      <el-dialog v-model="data.formVisible" title="加入购物车" width="500">
        <el-form
            :model="data.form"
            :rules="formRules"
            ref="formRef"
            label-width="110px"
        >
          <!-- 设置label-width统一标签宽度 -->
          <el-form-item label="药材名称：" prop="name">
            <el-input v-model="data.form.name" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="购买量(g)：" prop="count">
            <el-input v-model.number="data.form.count" placeholder="请输入购买量" @input="calculateAmount" />
          </el-form-item>
          <el-form-item label="金额(元)：" prop="amount">
            <el-input v-model="data.form.amount" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="售价(元/g)：" prop="sale_price">
            <el-input v-model="data.form.sale_price" autocomplete="off" disabled />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitOrder">确认订单</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { Search, ShoppingCart } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  ids: []
});

const value = ref('');
const hasSearched = ref(false); // 用于判断是否进行了查询

const formRef = ref(null);
const formRules = {
  count: [
    { required: true, message: '购买量不能为空', trigger: 'blur' },
    { type: 'number', message: '购买量必须为数字', trigger: 'blur' }
  ]
};

const options = [
  {
    value: '解表类',
    label: '解表类',
  },
  {
    value: '清热类',
    label: '清热类',
  },
  {
    value: '泻下类',
    label: '泻下类',
  },
  {
    value: '祛风湿类',
    label: '祛风湿类',
  },
  {
    value: '利水渗湿类',
    label: '利水渗湿类',
  },
  {
    value: '温理类',
    label: '温理类',
  },
  {
    value: '活血化瘀类',
    label: '活血化瘀类',
  },
  {
    value: '化痰止咳平喘类',
    label: '化痰止咳平喘类',
  },
  {
    value: '补虚类',
    label: '补虚类',
  },
];

const load = () => {
  hasSearched.value = true;
  request.get('/medicine/findAllMedicine', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      category: value.value
    }
  }).then(res => {
    data.tableData = res.data.content;
    data.total = res.data.page.totalElements;
  }).catch(error => {
    ElMessage.error('数据加载失败，请稍后重试');
    console.error(error);
  });
};

const rest = () => {
  data.name = null;
  value.value = null;
  data.tableData = [];
  hasSearched.value = false;
};

const submitOrder = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const user_name = JSON.parse(localStorage.getItem('user-name'));
      console.log(user_name)
      if (!user_name) {
        ElMessage.error('未获取到用户姓名，请重新登录');
        return;
      }
      const orderData = {
        user_name,
        name: data.form.name,
        count: data.form.count,
        price_sum: data.form.amount,
        amount: data.form.sale_price
      };
      console.log(orderData)
      request.post('/shop/addShop', orderData)
          .then(res => {
            if (res.code === 200) {
              data.formVisible = false;
              ElMessage.success('订单提交成功');
              load(); // 重新加载数据，确保显示最新的库存量
            } else {
              ElMessage.error(res.message);
            }
          })
          .catch(error => {
            ElMessage.error('订单提交失败，请稍后重试');
            console.error(error);
          });
    } else {
      ElMessage.error('请填写完整购买量');
    }
  });
};

const handleUpdate = (row) => {
  data.form = {...row};
  data.formVisible = true;
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id);
};

const calculateAmount = () => {
  const count = data.form.count;
  const salePrice = data.form.sale_price;
  if (count && salePrice) {
    data.form.amount = count * salePrice;
  } else {
    data.form.amount = 0;
  }
};
</script>

<style scoped>
.cards {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.12);
}

.el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.no-data-tip {
  font-size: 24px;
  margin-top: 15%;
  margin-left: -10%;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.8);
}
</style>